import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/data/team_entiy.dart';
import 'package:sports_new/entity/data/team_focus_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/data_api.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/my/my_focus_team_page.dart';
import 'package:sports_new/view/my/widgets/my_appbar.dart';

import 'package:sports_new/widgets/base/qkd_dialog.dart';

import '../../server/api/user_api.dart';
import '../../widgets/base/qkd_text.dart';

class My2FocusTeamPage extends StatefulWidget {
  const My2FocusTeamPage({super.key});

  @override
  State<My2FocusTeamPage> createState() => _My2FocusTeamPageState();
}

class _My2FocusTeamPageState extends State<My2FocusTeamPage> {

  List<FocusTeamListEntity> list = [];
  FocusTeamListEntity? selectTeam;
  List<MyTeamFocusEntity> get teams => selectTeam?.teamList ?? [];

  getTeams() async {
    list = await DataApi.teamForSelect() ?? [];
    if (list.isNotEmpty) {
      selectTeam = list.first;
    }
    update();
  }

  focusOrNot(MyTeamFocusEntity team) async {
    if (team.id == null) { return; }
    if (team.focus == 0) {
      Utils.onEvent('wd_wdgz_gzan', params: {'wd_wdgz_gzan': '4'});
      final result = await UserApi.focusTeam(team.id!,1);
      if (result == 200) {
        team.focus = 1;
        update();
      }
    } else {
      if (!await Get.dialog(QkdDialog.alert("确认不再关注？"))) { return; }
      final r = await UserApi.unFocusTeam(team.id!,1);
      if (r == 200) {
        team.focus = 0;
        update();
      } else {
        ToastUtils.showDismiss("取消关注失败");
      }
    }
  }

  @override
  void initState() {
    getTeams();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.scaffoldBg,
      appBar:const MyAppBar(title: "关注球队"),
      body: Row(
        children: [
          leftSide(),
          Expanded(child: rightSide())
        ],
      ),
    );
  }

  Widget leftCell(FocusTeamListEntity list) {
    final select = list == selectTeam;
    int num = 0;
    for (var element in list.teamList ?? []) {
      if (element.focus != 0) {
        num += 1;
      }
    }
    String name = list.leagueName ?? "";
    if (num != 0) {
      name = "${list.leagueName}($num)";
    }
    return Stack(
      children: [
        Container(
          color: select ? Colours.white : null,
          height: 60,
          alignment: Alignment.center,
          child: QkdText(name),
        ).tap(() { 
          selectTeam = list;
          update();
        }),
        if (select)
        Positioned(
          left: 0,top: 18, bottom: 18,
          child: Container(
            width: 3,
            height: 24,
            decoration: const BoxDecoration(
                color: Colours.main,
                borderRadius: BorderRadius.horizontal(right: Radius.circular(3))
            ),
          ))
      ],
    );
  }
  Widget leftSide() => Container(
    width: 80,
    child: ListView(children: [
      ...list.map((e) => leftCell(e))
    ],),
  );

  Widget rightCell(MyTeamFocusEntity team) => Container(
    padding: EdgeInsets.only(left: 20,right: 16),
    height: 50,
    child: Row(
      children: [
        Row(
          children: [
            Container(
              clipBehavior: Clip.hardEdge,
              width: 24,
              height: 24,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(2)),
              child: CachedNetworkImage(imageUrl: team.logo ?? "",
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (context, url, error) => Styles.placeholderIcon(),
              ),  
            ).marginOnly(right: 12),
            QkdText(team.nameChsShort ?? ""),
          ],
        ).tap(() { 
          Utils.onEvent('wd_wdgz_gzan', params: {'wd_wdgz_gzan': '5'});
          Get.toNamed(Routes.zqTeamDetail,arguments: team.id);
        }),
        const Spacer(),
        Container(
          width: 56,
          height: 24,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            border: Border.all(color: team.focus == 0 ? Colours.main : Colours.grey99,width: 0.5),
            borderRadius: BorderRadius.circular(4)
          ),
          child: QkdText(team.focus == 0 ? "关注" : "已关注",
            color: team.focus == 0 ? Colours.main : Colours.grey99,fontSize: 13
          ),
        ).tap(() { 
          focusOrNot(team);
        })
      ],
    ),
  );

  Widget rightSide() => Container(
    color: Colours.white,
    child: ListView(
      children: [
        ...teams.map((e) => rightCell(e))
      ],
    ),
  );
}